const mongoose = require('mongoose');
const News = require('../models/news.model');
//增
exports.add=function(req,res,next){
    var news = new News(req.body);
        news.save().then(data => {
        res.json(data);
  });
};
//删
exports.remove = function(req, res, next) {
    var ids = req.params.id;
    ids = ids.split(',');
    News.remove({ _id: { $in: ids } }, function(data) {
        res.json(data);
    });

};
//改
exports.update=function(req,res,next){
    const id=req.params.id;
    console.log(id);
    News.findByIdAndUpdate(id, {$set:req.body}).then(data => {
        res.json(data);
      });
};
//查
exports.query=function(req,res,next){
    var page  = req.body.page ? req.body.page :1;
    var rows = req.body.rows ? req.body.rows :5;
    var queryCondition = {};
    var newsCid=req.body.NewsCid;
    if(newsCid === undefined){
      res.json({message:"err message"});
      return;
    }else{
      newsCid=req.body.NewsCid;
      queryCondition={
        NewsCid:newsCid
      }
    }
    //模糊查询
    if (req.body.NewsTitle && req.body.NewsTitle.trim().length > 0){
        NewsTitle=req.body.NewsTitle;
        queryCondition =Object.assign(queryCondition,{
          NewsTitle: new RegExp(NewsTitle, 'i')
        })
    }
    News.paginate(queryCondition,{page:+page,limit:+rows},function(err,result){
		result.rows=result.docs;
		delete result.docs;
        res.json(result);
    });
};
exports.get = function(req, res, next) {
    const id = req.params.id;
    News.findById(id).then(data => {
      res.json(data);
    });
  };